package org.csu.mypetstore.service.impl;

import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.persistence.CartMapper;
import org.csu.mypetstore.persistence.ItemMapper;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("cartservice")
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemService itemService;

    // 添加商品到购物车方法
    @Transactional
    public void addToCart(String userId, String itemId, int quantity) {
        CartItem existingItem = cartMapper.selectCartItemByUserAndItem(userId, itemId);
        if (existingItem != null) {
            existingItem.setQuantity(existingItem.getQuantity() + quantity);
            cartMapper.updateQuantity(existingItem);
        } else {
            CartItem newItem = new CartItem();
            newItem.setUserId(userId);
            newItem.setItemId(itemId);
            newItem.setQuantity(quantity);
            cartMapper.insertCartItem(newItem);
        }
    }

    @Transactional(readOnly = true)
    public List<CartItem> getCartItems(String userId) {
        List<CartItem> cartItems = cartMapper.selectCartByUserId(userId);
        cartItems.forEach(item -> {
            // 获取商品详细信息
            Item itemDetail = itemService.getItemById(item.getItemId());
            item.setItem(itemDetail);
            // 计算总价
            item.calculateTotal();
        });
        return cartItems;
    }

    // 从购物车移除商品
    @Transactional
    public void removeFromCart(String userId, String itemId) {
        cartMapper.deleteCartItemByUserAndItem(userId, itemId);
    }

    @Override
    public void updateCartItem(String userId, String itemId, int quantity) {
        // 1. 验证数量有效性
        if (quantity <= 0) {
            throw new IllegalArgumentException("数量必须大于0");
        }

        // 2. 检查商品是否存在
        Item item = cartMapper.getItemById(itemId);
        if (item == null) {
            throw new RuntimeException("商品不存在: " + itemId);
        }

        // 3. 更新购物车项
        int updated = cartMapper.updateCartItemQuantity(userId, itemId, quantity);
        if (updated == 0) {
            // 如果不存在则新增
            cartMapper.addItemToCart(userId, itemId, quantity);
        }
    }

}
